package com.example.web.demos.crypto;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public class EncryptionUtils {

    // 密钥，通常你应该从配置中读取
    private static final String SECRET_KEY = "xK4@bA7=tH7$wA7[vP6";  // 16个字节的密钥
    private static final String ALGORITHM = "AES";

    // 加密方法
    public static String encrypt(String data) throws Exception {
        SecretKeySpec keySpec = new SecretKeySpec(SECRET_KEY.getBytes(), ALGORITHM);
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, keySpec);
        byte[] encryptedData = cipher.doFinal(data.getBytes());
        return Base64.getEncoder().encodeToString(encryptedData);
    }

    // 解密方法
    public static String decrypt(String encryptedData) throws Exception {
        SecretKeySpec keySpec = new SecretKeySpec(SECRET_KEY.getBytes(), ALGORITHM);
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, keySpec);
        byte[] decodedData = Base64.getDecoder().decode(encryptedData);
        byte[] decryptedData = cipher.doFinal(decodedData);
        return new String(decryptedData);
    }

    public static void main(String[] args) throws Exception {
//        String originalData = "2405da3eecf07e6d77f1b9c3bd2f268103189b3d510e5da51062b48a4049e91ae750d9e3e5e1f2ca9026061284b46dc6"; // 示例数据
//        String encryptedData = encrypt(originalData);
//        System.out.println("Encrypted: " + encryptedData);

//        String decryptedData = decrypt("2405da3eecf07e6d77f1b9c3bd2f268103189b3d510e5da51062b48a4049e91ae750d9e3e5e1f2ca9026061284b46dc6");
//        System.out.println("Decrypted: " + decryptedData);

//        DesCbcCrcEType encryptor = new DesCbcCrcEType();
//        new String(Hex.encode(encryptor.encrypt(Utf8.encode("123456"))))
    }
}

/**
 * @author scout.du
 * @date 2024/12/30 11:13
 **/

